package com.year.shiyi.aspect;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.gson.Gson;
import com.year.shiyi.annotation.SysLog;
import com.year.shiyi.entity.mybatis.SysLogEntity;
import com.year.shiyi.entity.mybatis.SysUserEntity;
import com.year.shiyi.service.SysLogService;
import com.year.shiyi.common.utils.http.HttpContextUtils;
import com.year.shiyi.common.utils.http.IPUtils;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @author shiyi on 2021/2/20 11:13
 */
@Aspect
@Component
public class SysLogAspect {

    @Autowired
    private SysLogService sysLogService;

    @Pointcut("@annotation(com.year.shiyi.annotation.SysLog)")
    public void logPointCut() {

    }


    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        //执行方法
        Object result = point.proceed();
        //执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;
        //保存日志
        saveSysLog(point, time);
        return result;
    }

    private void saveSysLog(ProceedingJoinPoint point, long time) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        SysLogEntity entity = new SysLogEntity();
        SysLog annotation = method.getAnnotation(SysLog.class);
        // 注解
        if (annotation != null) {
            entity.setOperation(annotation.value());
        }

        String className = point.getTarget().getClass().getName();
        String methodName = signature.getName();
        entity.setMethod(className + "." + methodName + "()");

        Object[] args = point.getArgs();
        try {
            String params = JSON.toJSONString(args, SerializerFeature.IgnoreNonFieldGetter);
//            String params = new Gson().toJson(args);
            entity.setParams(params);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        //获取request
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        //设置IP地址
        entity.setIp(IPUtils.getIpAddr(request));

        //用户名
        String username = ((SysUserEntity) SecurityUtils.getSubject().getPrincipal()).getUsername();
        entity.setUsername(username);

        entity.setTime(time);
        entity.setCreateDate(new Date());
        //保存系统日志
        sysLogService.save(entity);
    }

}
